#include "ConstantBuffer.h"

namespace devii
{

ConstantBuffer::ConstantBuffer(ID3D11Device* device, ID3D11DeviceContext* context) : Buffer(device, context)
{
	constant_buffer = 0;
}

ConstantBuffer::~ConstantBuffer()
{
	if(constant_buffer)
	{
		constant_buffer->Release();
		constant_buffer = 0;
	}
}


bool ConstantBuffer::init(const unsigned int size, const unsigned int offset)
{
	D3D11_BUFFER_DESC cbDesc;
	ZeroMemory(&cbDesc, sizeof(cbDesc));
	cbDesc.ByteWidth = size;
	cbDesc.StructureByteStride = offset;
	cbDesc.Usage = D3D11_USAGE_DYNAMIC;
	cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	cbDesc.MiscFlags = 0;
	cbDesc.StructureByteStride = 0;

	HRESULT hr = device->CreateBuffer(&cbDesc, NULL, &constant_buffer);

	if(SUCCEEDED(hr))
		return true;
	return false;
}

ID3D11Buffer* ConstantBuffer::getBuffer() const
{
	return constant_buffer;
}

HRESULT ConstantBuffer::map(const unsigned int sub_resource, D3D11_MAP map, D3D11_MAPPED_SUBRESOURCE* resource)
{
	return context->Map(constant_buffer, sub_resource, map, 0, resource);
}

void ConstantBuffer::unmap(const unsigned int sub_resource)
{
	context->Unmap(constant_buffer, sub_resource);
}


}